package com.wontube.core.dao;

import java.util.Stack;

import org.apache.ibatis.session.SqlSession;

/**
 * 
 * @author yuechao
 * 
 *         本地 SqlSession
 * 
 */
public final class DatasourceContext {
	private DatasourceContext() {
	}

	/**
	 * 线程变量：事务
	 * 
	 */
	private static final ThreadLocal<SqlSession> __session = new ThreadLocal<SqlSession>();

	/**
	 * 事务堆栈
	 * 
	 */
	private static final ThreadLocal<Stack<SqlSession>> __stack = new ThreadLocal<Stack<SqlSession>>();

	/**
	 * 获取当前事务
	 * 
	 * @return
	 */
	public static SqlSession getSqlSession() {
		return __session.get();
	}

	/**
	 * 关闭当前事务
	 * 
	 */
	public static void close() {
		SqlSession session = __session.get();
		if (session != null) {
			session.close();
			__session.remove();
		}
	}

	/**
	 * 设置当前事务
	 * 
	 * @param sms
	 */
	public static void setTrans(SqlSession sms) {
		if (sms == null) {
			__session.remove();
		} else {
			__session.set(sms);
		}
	}

	/**
	 * 推入事务
	 * 
	 */
	public static void open(SqlSession sms) {
		Stack<SqlSession> stack = __stack.get();
		if (stack == null) {
			stack = new Stack<SqlSession>();
			__stack.set(stack);
		}

		SqlSession current = __session.get();
		if (current != null) {
			if (stack.size() == 0 || current != stack.peek()) {
				stack.push(current);
			}
		}

		stack.push(sms);
		__session.set(sms);
	}

	/**
	 * 还原事务
	 * 
	 */
	public static void restore() {
		Stack<SqlSession> stack = __stack.get();

		if (stack.size() > 0) {
			SqlSession session = stack.pop();
			if (session != null) {
				session.close();
			}

			if (stack.size() > 0) {
				__session.set(stack.peek());
			} else {
				__session.remove();
			}
		}
	}
}
